﻿using Microsoft.AspNetCore.SignalR;
using Rssdp;

namespace WebDAV;

public class DlnaDiscoveryService
{
    private readonly SsdpDeviceLocator _locator = new();

    public async Task DiscoverDevicesAsync(IHubContext<ScreenShareHub> hubContext)
    {
        Console.WriteLine("Searching for DLNA devices...");
        _locator.DeviceAvailable += async (sender, e) => 
        {
            var device = e.DiscoveredDevice;
            var deviceInfo = await device.GetDeviceInfo();
            Console.WriteLine($"Discovered device: {deviceInfo.FriendlyName} ({device.DescriptionLocation})");
            await hubContext.Clients.All.SendAsync("DeviceDiscovered", 
                $"{deviceInfo.FriendlyName} ({device.DescriptionLocation})");
        };
        await _locator.SearchAsync();
    }
    
    public async void SearchForDevices()
    {
        // This code goes in a method somewhere.
        using var deviceLocator = new SsdpDeviceLocator();
        var foundDevices = await deviceLocator.SearchAsync(); // Can pass search arguments here (device type, uuid). No arguments means all devices.

        foreach (var foundDevice in foundDevices)
        {
            // Device data returned only contains basic device details and location ]
            // of full device description.
            Console.WriteLine("Found " + foundDevice.Usn + " at " + foundDevice.DescriptionLocation);
            
            // Can retrieve the full device description easily though.
            var fullDevice = await foundDevice.GetDeviceInfo();
            Console.WriteLine(fullDevice.FriendlyName);
            Console.WriteLine();
        }
    }
}